import pandas as pd
import numpy as np
import math
import datetime
from tabulate import tabulate
import time

def main(type):
    #LinshiJob.py
    '''
    临时分配
    读取当前时刻（上一时刻）的分配矩阵，主机资源矩阵
    读取上一时刻的服务相关数据
    读取新增的服务相关数据（副本个数只考虑新增）
    '''
    def printtime(str_tmp):
        now = datetime.datetime.now()
        print('['+str(now)+']'+str(str_tmp))
    message = ''
    xlsx_name = 'D:/repos/sicost/MNbest_sx_new2.xlsx'
    df_sx_new = pd.read_excel(xlsx_name)
    printtime('当前服务调度方案')
    print(tabulate(df_sx_new, headers="keys", tablefmt="pretty"))
    xlsx_name = 'D:/repos/sicost/模拟主机相关数据.xlsx'
    df_m = pd.read_excel(xlsx_name)
    printtime('主机相关数据矩阵')
    print(tabulate(df_m, headers="keys", tablefmt="pretty"))
    xlsx_name = 'D:/repos/sicost/模拟服务相关数据.xlsx'
    df_s = pd.read_excel(xlsx_name)
    printtime('服务相关数据矩阵')
    print(tabulate(df_s, headers="keys", tablefmt="pretty"))
    df_m['RESOURCE'] = df_m['RESOURCE'] * 2
    df_s['COPY_SIZE'] = df_s['COPY_SIZE'] * 2
    df_sx_new['COPY_SIZE'] = df_sx_new['COPY_SIZE'] * 2
    machine_name_list = df_m['MACHINE_NAME'].tolist()
    machine_count = len(machine_name_list)
    ###解析数据
    printtime('解析服务调度矩阵')
    sx_1_columns = machine_name_list.copy()
    sx_1_columns.append('SERVICE_NAME')
    df_sx_1 = pd.DataFrame(columns=sx_1_columns)
    dict_sx_1 = {}
    for index, row in df_sx_new.iterrows():
        service_name_tmp = row['SERVICE_NAME']
        plan_dict_str = row['PLAN']
        plan_dict_tmp = eval(plan_dict_str)
        for i in range(0, len(machine_name_list)):
            machine_name_tmp = machine_name_list[i]
            service_count_tmp = plan_dict_tmp[machine_name_tmp]
            dict_sx_1[machine_name_tmp] = service_count_tmp
        dict_sx_1['SERVICE_NAME'] = service_name_tmp
        new_row = pd.Series(dict_sx_1)
        df_sx_1 = df_sx_1.append(new_row, ignore_index=True)
    df_sx_new2 = df_sx_new[['SERVICE_NAME', 'SERVICE_NO', 'COPY_NUM', 'COPY_SIZE', 'ISOLATION']]
    v = ['SERVICE_NAME']
    df_sx_0 = pd.merge(df_sx_new2, df_sx_1, on=v, how='left')
    printtime('当前服务调度矩阵')
    print(tabulate(df_sx_0, headers="keys", tablefmt="pretty"))
    ###解析主机资源使用情况
    df_m_1 = pd.DataFrame(columns=['MACHINE_NAME', 'RESOURCE_A'])
    dict_m_1 = {}
    for i in range(0, len(machine_name_list)):
        machine_name_tmp = machine_name_list[i]
        dict_m_1['MACHINE_NAME'] = machine_name_tmp
        df_sx_2 = df_sx_0.copy()
        df_sx_2['RESOURCE_A'] = df_sx_2[machine_name_tmp] * df_sx_2['COPY_SIZE']
        resource_a_tmp = df_sx_2['RESOURCE_A'].sum()
        dict_m_1['RESOURCE_A'] = resource_a_tmp
        new_row = pd.Series(dict_m_1)
        df_m_1 = df_m_1.append(new_row, ignore_index=True)
    v = ['MACHINE_NAME']
    df_m_0 = pd.merge(df_m, df_m_1, on=v, how='left')
    df_m_0['LEFT_RESOURCE'] = df_m_0['RESOURCE'] - df_m_0['RESOURCE_A']
    sorted_df_m_0 = df_m_0.sort_values(by='LEFT_RESOURCE', ascending=False)
    sorted_df_m_0 = sorted_df_m_0.reset_index(drop=True)
    ###读取新增的服务相关数据（副本个数只考虑新增）
    xlsx_name = 'D:/repos/sicost/临时服务2.xlsx'
    df_s_add = pd.read_excel(xlsx_name)
    df_s_add['COPY_SIZE2'] = df_s_add['COPY_SIZE2'] * 2

    # 优先放置需要隔离的
    v = ['SERVICE_NAME']
    df_s_add_0 = pd.merge(df_s, df_s_add, on=v, how='outer')
    # 理论上 副本大小与反亲和性不会发生改变，同时拥有取后者
    df_s_add_0.fillna('', inplace=True)
    def __cal_copy_size_true(x):
        if x.COPY_SIZE2 == '':
            rst = x.COPY_SIZE
        else:
            rst = x.COPY_SIZE2
        return rst
    df_s_add_0['COPY_SIZE_TRUE'] = df_s_add_0.apply(lambda x: __cal_copy_size_true(x), axis=1)
    def __cal_isolation_true(x):
        if x.ISOLATION2 == '':
            rst = x.ISOLATION
        else:
            rst = x.ISOLATION2
        return rst
    df_s_add_0['ISOLATION_TRUE'] = df_s_add_0.apply(lambda x: __cal_isolation_true(x), axis=1)
    df_s_add_0.drop(['ISOLATION'], axis=1, inplace=True)
    df_s_add_0.drop(['ISOLATION2'], axis=1, inplace=True)
    df_s_add_0.drop(['COPY_SIZE'], axis=1, inplace=True)
    df_s_add_0.drop(['COPY_SIZE2'], axis=1, inplace=True)
    # 新服务需要隔离
    df_group1 = df_s_add_0[(df_s_add_0['COPY_NUM'] == '') & (df_s_add_0['ISOLATION_TRUE'] == 1)]
    df_group1 = df_group1.reset_index(drop=True)
    # 旧服务需要隔离
    df_group2 = df_s_add_0[(df_s_add_0['COPY_NUM'] != '') & (df_s_add_0['COPY_NUM2'] != '') & (df_s_add_0['ISOLATION_TRUE'] == 1)]
    df_group2 = df_group2.reset_index(drop=True)
    # 新服务不需隔离
    df_group3 = df_s_add_0[(df_s_add_0['COPY_NUM'] == '') & (df_s_add_0['COPY_NUM2'] != '') & (df_s_add_0['ISOLATION_TRUE'] == 0)]
    df_group3 = df_group3.reset_index(drop=True)
    # 旧服务不需隔离
    df_group4 = df_s_add_0[(df_s_add_0['COPY_NUM'] != '') & (df_s_add_0['COPY_NUM2'] != '') & (df_s_add_0['ISOLATION_TRUE'] == 0)]
    df_group4 = df_group4.reset_index(drop=True)
    df_group5 = pd.DataFrame(columns=['SERVICE_NAME', 'COPY_NUM', 'COPY_NUM2', 'COPY_SIZE_TRUE', 'ISOLATION_TRUE'])
    df_m_01 = df_m_0.copy()
    #实际能装的剩余资源量(满足主机本身的使用率上限)
    df_m_01['LEFT_RESOURCE_TRUE'] = df_m_01['RESOURCE'] * df_m_01['U_MAX'] / 100 - df_m_01['RESOURCE_A']
    def __cal_flag(x):
        if x.LEFT_RESOURCE == x.RESOURCE:
            rst = 0
        else:
            rst = 1
        return rst
    df_m_01['FLAG'] = df_m_01.apply(lambda x: __cal_flag(x), axis=1)
    df_sx_01 = df_sx_0.copy()
    service_no_max = int(df_sx_01['SERVICE_NO'].max())
    df_m_01 = df_m_01.reset_index(drop=False)
    df_m_01.rename(columns={'index': 'MACHINE_NO'}, inplace=True)
    ####
    df_out1 = df_s_add.copy()
    for machine_name_tmp in machine_name_list:
        df_out1[machine_name_tmp] = 0
    # group5需要写入到df_out2
    df_out2 = pd.DataFrame(
                columns=['SERVICE_NAME', 'COPY_NAME', 'COPY_SIZE', 'ISOLATION', 'OLD_PLAN', 'NEW_PLAN'])
    df_fanqinhe1 = pd.DataFrame(
        columns=['SERVICE_NAME', 'COPY_NUM', 'COPY_NUM2', 'COPY_SIZE_TRUE', 'ISOLATION_TRUE'])
    df_fanqinhe2 = pd.DataFrame(
        columns=['SERVICE_NAME', 'COPY_NUM', 'COPY_NUM2', 'COPY_SIZE_TRUE', 'ISOLATION_TRUE'])
    ################
    # #group1的分配代码
    # 判断group1是否为空
    success = df_group1.empty is False
    # success = True
    if success is False:
        # print('跳过df_group1')
        message = ''
    else:
        df_group1_tmp0 = df_group1.copy()
        #排序，优先分配副本多的服务
        #     #反亲和逻辑修改
        #对group1的所有服务的copy_num进行判断是否超过总机器数，如果超过，将超过部分更新到group4中，并更新group1中的copy_num
        # df_group1_tmp['COPY_NUM_SUM'] = df_group1_tmp['COPY_NUM'] + df_group1_tmp['COPY_NUM2']
        df_group1_tmp0['COPY_NUM_SUM'] = df_group1_tmp0['COPY_NUM2']
        #测试代码
        machine_count = 2
        def __cal_copy_num3(x):
            if x.COPY_NUM_SUM > machine_count:
                rst = machine_count
            else:
                rst = x.COPY_NUM2
            return rst
        df_group1_tmp0['COPY_NUM3'] = df_group1_tmp0.apply(lambda x: __cal_copy_num3(x), axis=1)
        def __cal_copy_num4(x):
            if x.COPY_NUM_SUM > machine_count:
                rst = x.COPY_NUM_SUM - machine_count
            else:
                rst = 0
            return rst
        df_group1_tmp0['COPY_NUM4'] = df_group1_tmp0.apply(lambda x: __cal_copy_num4(x), axis=1)
        df_group1_tmp1 = df_group1_tmp0[df_group1_tmp0['COPY_NUM2'] > 0]
        success = df_group1_tmp1.empty is False
        # success = True
        if success is False:
            print('没有超过主机数量的反亲和服务')
            df_group1_tmp = df_group1.copy()
            sorted_df_group1_tmp = df_group1_tmp.sort_values(by='COPY_NUM2', ascending=False)
            sorted_df_group1_tmp = sorted_df_group1_tmp.reset_index(drop=True)
        else:
            print('有超过主机数量的反亲和服务')
            for index, row in df_group1_tmp0.iterrows():
                if row['COPY_NUM4'] > 0:
                    fanqinhe_dict1 = {}
                    fanqinhe_dict1['SERVICE_NAME'] = row['SERVICE_NAME']
                    fanqinhe_dict1['COPY_NUM'] = row['COPY_NUM']
                    fanqinhe_dict1['COPY_NUM2'] = row['COPY_NUM4']
                    fanqinhe_dict1['COPY_SIZE_TRUE'] = row['COPY_SIZE_TRUE']
                    fanqinhe_dict1['ISOLATION_TRUE'] = row['ISOLATION_TRUE']
                    new_row = pd.Series(fanqinhe_dict1)
                    df_fanqinhe1 = df_fanqinhe1.append(new_row, ignore_index=True)
            #拼接到group4后
            df_group4 = pd.concat([df_group4, df_fanqinhe1], axis=0)
            df_group4 = df_group4.reset_index(drop=True)
            #生成全新的group1的数据
            df_group1_tmp0.drop(['COPY_NUM2'], axis=1, inplace=True)
            df_group1_tmp0.rename(columns={'COPY_NUM3': 'COPY_NUM2'}, inplace=True)
            df_group1_tmp0.drop(['COPY_NUM4'], axis=1, inplace=True)
            sorted_df_group1_tmp = df_group1_tmp0.sort_values(by='COPY_NUM2', ascending=False)
            sorted_df_group1_tmp = sorted_df_group1_tmp.reset_index(drop=True)

        dict_sx_01 = {}
        for index, row in sorted_df_group1_tmp.iterrows():
            #在服务df最后一行拼接上新服务
            printtime(f"当前服务: {row['SERVICE_NAME']} ")
            # print(row['SERVICE_NAME'])
            service_name_tmp = row['SERVICE_NAME']
            copy_size_tmp = row['COPY_SIZE_TRUE']
            copy_num2_tmp = int(row['COPY_NUM2'])
            # sorted_df_m_01 = df_m_01.sort_values(by='LEFT_RESOURCE_TRUE', ascending=False)
            sorted_df_m_01 = df_m_01.sort_values(by=['FLAG', 'LEFT_RESOURCE_TRUE'], ascending=[False, False])
            sorted_df_m_01 = sorted_df_m_01.reset_index(drop=True)
            dict_sx_01['SERVICE_NAME'] = service_name_tmp
            service_no_tmp = int(service_no_max + 1)
            dict_sx_01['SERVICE_NO'] = service_no_tmp
            service_no_max = service_no_max + 1
            dict_sx_01['COPY_NUM'] = copy_num2_tmp
            dict_sx_01['COPY_SIZE'] = copy_size_tmp
            dict_sx_01['ISOLATION'] = 1
            new_row = pd.Series(dict_sx_01)
            df_sx_01 = df_sx_01.append(new_row, ignore_index=True)
            df_sx_01.fillna(0, inplace=True)
            machine_name_list_tmp1 = sorted_df_m_01['MACHINE_NAME'].tolist()
            machine_no_list_tmp1 = sorted_df_m_01['MACHINE_NO'].tolist()
            a = 0
            for i in range(0, copy_num2_tmp):
                row_tmp = int(i + a)
                if row_tmp > len(sorted_df_m_01.index) - 1:
                    print('无机器可用')
                for j in range(row_tmp, len(sorted_df_m_01.index)):
                    # print(j)
                    flag = False
                    machine_name_tmp1 = machine_name_list_tmp1[j]
                    machine_no_tmp1 = int(machine_no_list_tmp1[j])
                    left_resource_true_tmp1 = df_m_01.loc[machine_no_tmp1, 'LEFT_RESOURCE_TRUE']
                    if left_resource_true_tmp1 >= copy_size_tmp:
                        #当前主机能装下这个副本
                        df_m_01.loc[machine_no_tmp1, 'RESOURCE_A'] = df_m_01.loc[machine_no_tmp1, 'RESOURCE_A'] + copy_size_tmp
                        df_m_01.loc[machine_no_tmp1, 'LEFT_RESOURCE'] = df_m_01.loc[machine_no_tmp1, 'LEFT_RESOURCE'] - copy_size_tmp
                        df_m_01.loc[machine_no_tmp1, 'LEFT_RESOURCE_TRUE'] = df_m_01.loc[machine_no_tmp1, 'LEFT_RESOURCE_TRUE'] - copy_size_tmp
                        # machine_name_tmp_list.append(machine_name_tmp)
                        df_sx_01.loc[service_no_tmp, machine_name_tmp1] = 1
                        df_out1.loc[df_out1['SERVICE_NAME'] == service_name_tmp, machine_name_tmp1] += 1
                        #分配成功
                        #跳出主机循环，进入下一个服务
                        # 进入下一服务i会加一，a不用增加
                        flag = True
                    else:
                        print('当前主机剩余空间装不下这个副本，由于主机排序了，前一个装不下后一个也装不下，因此需要微调')
                        #该主机所有不需要隔离的服务副本
                        df_sx_01_tmp = df_sx_01[(df_sx_01['ISOLATION'] != 1) & (df_sx_01[machine_name_tmp1] >= 1)]
                        sorted_df_sx_01_tmp = df_sx_01_tmp.sort_values(by='COPY_SIZE', ascending=False)
                        sorted_df_sx_01_tmp = sorted_df_sx_01_tmp.reset_index(drop=True)
                        sorted_df_sx_01_tmp['TOTAL_R'] = sorted_df_sx_01_tmp[machine_name_tmp1] * sorted_df_sx_01_tmp['COPY_SIZE']
                        total_r_sum = sorted_df_sx_01_tmp['TOTAL_R'].sum()
                        #判断该主机亲和的副本资源总量是否能装下这个副本
                        if total_r_sum + left_resource_true_tmp1 < copy_size_tmp:
                            print('这个主机装不了，换下一个主机')
                            a = a + 1
                            #走主机循环
                            continue
                        else:
                            print('这个主机可以装')
                            rr = copy_size_tmp
                            dict_group5 = {}
                            for index2, row2 in sorted_df_sx_01_tmp.iterrows():
                                # 判断这个亲和服务的副本资源总量是否能装下
                                if row2['TOTAL_R'] + left_resource_true_tmp1 >= rr:
                                    print('这个服务部分或全部移走，不需要其他服务')
                                    n = math.ceil((rr - left_resource_true_tmp1) / row2['COPY_SIZE'])
                                    df_m_01.loc[machine_no_tmp1, 'RESOURCE_A'] = df_m_01.loc[machine_no_tmp1, 'RESOURCE_A'] + rr - n * row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp1, 'LEFT_RESOURCE'] = df_m_01.loc[machine_no_tmp1, 'LEFT_RESOURCE'] - rr + n * row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp1, 'LEFT_RESOURCE_TRUE'] = df_m_01.loc[machine_no_tmp1, 'LEFT_RESOURCE_TRUE'] - rr + n * row2['COPY_SIZE']
                                    df_sx_01.loc[service_no_tmp, machine_name_tmp1] = 1
                                    move_service_no_tmp = row2['SERVICE_NO']
                                    df_sx_01.loc[move_service_no_tmp, machine_name_tmp1] = df_sx_01.loc[move_service_no_tmp, machine_name_tmp1] - n
                                    df_out1.loc[df_out1['SERVICE_NAME'] == service_name_tmp, machine_name_tmp1] += 1

                                    #需要挪走的先放到group5，最后和group4一起分配
                                    dict_group5['SERVICE_NAME'] = row2['SERVICE_NAME']
                                    dict_group5['COPY_NUM2'] = n
                                    dict_group5['COPY_SIZE_TRUE'] = row2['COPY_SIZE']
                                    dict_group5['ISOLATION_TRUE'] = 0
                                    new_row2 = pd.Series(dict_group5)
                                    df_group5 = df_group5.append(new_row2, ignore_index=True)
                                    flag = True
                                    a = a + 1
                                    break
                                else:
                                    print('这个服务全部移走，并需要其他服务')
                                    n = row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp1, 'RESOURCE_A'] = df_m_01.loc[machine_no_tmp1, 'RESOURCE_A'] + rr - n * row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp1, 'LEFT_RESOURCE'] = df_m_01.loc[machine_no_tmp1, 'LEFT_RESOURCE'] - rr + n * row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp1, 'LEFT_RESOURCE_TRUE'] = df_m_01.loc[machine_no_tmp1, 'LEFT_RESOURCE_TRUE'] - rr + n * row2['COPY_SIZE']
                                    # df_sx_01.loc[service_no_tmp, machine_name_tmp1] = 1
                                    move_service_no_tmp = row2['SERVICE_NO']
                                    df_sx_01.loc[move_service_no_tmp, machine_name_tmp1] = df_sx_01.loc[move_service_no_tmp, machine_name_tmp1] - n
                                    rr = rr - n * row2['COPY_SIZE']
                                    dict_group5['SERVICE_NAME'] = row2['SERVICE_NO']
                                    dict_group5['COPY_NUM2'] = n
                                    dict_group5['COPY_SIZE_TRUE'] = row2['COPY_SIZE']
                                    dict_group5['ISOLATION_TRUE'] = 0
                                    new_row2 = pd.Series(dict_group5)
                                    df_group5 = df_group5.append(new_row2, ignore_index=True)
                                    flag = True
                                    continue
                            #分配成功
                            # continue
                    #如果分配成功就考虑下一个副本，跳出主机循环
                    if flag:
                        break
            # print('stop')
    #####################group1分配完毕
    # 判断group2是否为空
    success = df_group2.empty is False
    # success = True
    if success is False:
        # print('跳过df_group2')
        message = ''
    else:
        df_group2_tmp0 = df_group2.copy()
        # 对group2的所有服务的copy_num进行判断是否超过总机器数，如果超过，将超过部分更新到group4中，并更新group2中的copy_num
        df_group2_tmp0['COPY_NUM_SUM'] = df_group2_tmp0['COPY_NUM'] + df_group2_tmp0['COPY_NUM2']
        # 测试代码
        # machine_count = 2
        def __cal_copy_num3(x):
            if x.COPY_NUM_SUM > machine_count:
                rst = machine_count
            else:
                rst = x.COPY_NUM2
            return rst

        df_group2_tmp0['COPY_NUM3'] = df_group2_tmp0.apply(lambda x: __cal_copy_num3(x), axis=1)

        def __cal_copy_num4(x):
            if x.COPY_NUM_SUM > machine_count:
                rst = x.COPY_NUM_SUM - machine_count
            else:
                rst = 0
            return rst

        df_group2_tmp0['COPY_NUM4'] = df_group2_tmp0.apply(lambda x: __cal_copy_num4(x), axis=1)
        df_group2_tmp0 = df_group2_tmp0[df_group2_tmp0['COPY_NUM4'] > 0]
        success = df_group2_tmp0.empty is False
        # success = True
        if success is False:
            printtime('没有超过主机数量的反亲和服务')
            df_group2_tmp = df_group2.copy()
            # 排序，优先分配总副本多的服务
            df_group2_tmp['COPY_NUM_TRUE'] = df_group2_tmp['COPY_NUM'] + df_group2_tmp['COPY_NUM2']
            # 拼接service_no
            df_service_no = df_sx_01.copy()
            df_service_no = df_service_no[['SERVICE_NAME', 'SERVICE_NO']]
            v = ['SERVICE_NAME']
            df_group2_tmp = pd.merge(df_group2_tmp, df_service_no, on=v, how='left')
            sorted_df_group2_tmp = df_group2_tmp.sort_values(by='COPY_NUM_TRUE', ascending=False)
            sorted_df_group2_tmp = sorted_df_group2_tmp.reset_index(drop=True)
        else:
            printtime('有超过主机数量的反亲和服务')
            for index, row in df_group2_tmp0.iterrows():
                if row['COPY_NUM4'] > 0:
                    fanqinhe_dict2 = {}
                    fanqinhe_dict2['SERVICE_NAME'] = row['SERVICE_NAME']
                    fanqinhe_dict2['COPY_NUM'] = row['COPY_NUM']
                    fanqinhe_dict2['COPY_NUM2'] = row['COPY_NUM4']
                    fanqinhe_dict2['COPY_SIZE_TRUE'] = row['COPY_SIZE_TRUE']
                    fanqinhe_dict2['ISOLATION_TRUE'] = row['ISOLATION_TRUE']
                    new_row = pd.Series(fanqinhe_dict2)
                    df_fanqinhe2 = df_fanqinhe2.append(new_row, ignore_index=True)
            # 拼接到group4后
            df_group4 = pd.concat([df_group4, df_fanqinhe2], axis=0)
            df_group4 = df_group4.reset_index(drop=True)
            # 生成全新的group1的数据
            df_group2_tmp0.drop(['COPY_NUM2'], axis=1, inplace=True)
            df_group2_tmp0.rename(columns={'COPY_NUM3': 'COPY_NUM2'}, inplace=True)
            df_group2_tmp0.drop(['COPY_NUM4'], axis=1, inplace=True)
            df_group2_tmp0['COPY_NUM_TRUE'] = df_group2_tmp0['COPY_NUM'] + df_group2_tmp0['COPY_NUM2']
            # 拼接service_no
            df_service_no = df_sx_01.copy()
            df_service_no = df_service_no[['SERVICE_NAME', 'SERVICE_NO']]
            v = ['SERVICE_NAME']
            df_group2_tmp0 = pd.merge(df_group2_tmp0, df_service_no, on=v, how='left')
            sorted_df_group2_tmp = df_group2_tmp0.sort_values(by='COPY_NUM_TRUE', ascending=False)
            sorted_df_group2_tmp = sorted_df_group2_tmp.reset_index(drop=True)
        for index, row in sorted_df_group2_tmp.iterrows():
            # 在服务df上修改原服务的copy_num
            printtime(f"当前服务: {row['SERVICE_NAME']} ")
            # print(row['SERVICE_NAME'])
            service_name_tmp = row['SERVICE_NAME']
            service_no_tmp = int(row['SERVICE_NO'])
            copy_size_tmp = row['COPY_SIZE_TRUE']
            df_sx_01.loc[service_no_tmp, 'COPY_NUM'] = row['COPY_NUM_TRUE']
            #读取该服务没有部署的主机,还能用的主机
            printtime('读取该服务没有部署的主机')
            machine_name_list_tmp = []
            machine_no_list_tmp = []
            for i in range(0, len(machine_name_list)):
                machine_name_tmp = machine_name_list[i]
                # b = df_sx_01.loc[service_no_tmp, machine_name_tmp]
                if df_sx_01.loc[service_no_tmp, machine_name_tmp] == 0:
                    machine_name_list_tmp.append(machine_name_tmp)
                    machine_no_list_tmp.append(i)
            #循环copy放进这个这个主机列表中
            printtime(f"服务: {service_name_tmp}还能部署的主机:{machine_name_list_tmp} ")
            copy_num2_tmp = int(row['COPY_NUM2'])
            df_m_02 = df_m_01.copy()
            df_m_02 = df_m_02.iloc[machine_no_list_tmp]
            # sorted_df_m_02 = df_m_02.sort_values(by='LEFT_RESOURCE_TRUE', ascending=False)
            sorted_df_m_02 = df_m_02.sort_values(by=['FLAG', 'LEFT_RESOURCE_TRUE'], ascending=[False, False])

            sorted_df_m_02 = sorted_df_m_02.reset_index(drop=True)
            machine_name_list_tmp2 = sorted_df_m_02['MACHINE_NAME'].tolist()
            machine_no_list_tmp2 = sorted_df_m_02['MACHINE_NO'].tolist()
            a = 0
            for i in range(0, copy_num2_tmp):
                row_tmp = int(i + a)
                if row_tmp > len(machine_name_list_tmp2) - 1:
                    print('无机器可用')
                for j in range(row_tmp, len(machine_name_list_tmp2)):
                    # print(j)
                    flag = False
                    machine_name_tmp2 = machine_name_list_tmp2[j]
                    machine_no_tmp2 = int(machine_no_list_tmp2[j])
                    printtime(f"当前主机: {machine_name_tmp2} ")
                    left_resource_true_tmp2 = df_m_01.loc[machine_no_tmp2, 'LEFT_RESOURCE_TRUE']
                    if left_resource_true_tmp2 >= copy_size_tmp:
                        # 当前主机能装下这个副本
                        printtime('当前主机能装下这个副本')
                        df_m_01.loc[machine_no_tmp2, 'RESOURCE_A'] = df_m_01.loc[machine_no_tmp2, 'RESOURCE_A'] + copy_size_tmp
                        df_m_01.loc[machine_no_tmp2, 'LEFT_RESOURCE'] = df_m_01.loc[machine_no_tmp2, 'LEFT_RESOURCE'] - copy_size_tmp
                        df_m_01.loc[machine_no_tmp2, 'LEFT_RESOURCE_TRUE'] = df_m_01.loc[machine_no_tmp2, 'LEFT_RESOURCE_TRUE'] - copy_size_tmp
                        # machine_name_tmp_list.append(machine_name_tmp)
                        df_sx_01.loc[service_no_tmp, machine_name_tmp2] = 1
                        df_out1.loc[df_out1['SERVICE_NAME'] == service_name_tmp, machine_name_tmp2] += 1
                        printtime('分配成功')
                        # 分配成功
                        # 跳出主机循环，进入下一个服务
                        flag = True
                    else:
                        print('当前主机剩余空间装不下这个副本，由于主机排序了，前一个装不下后一个也装不下，因此需要微调')
                        # 该主机所有不需要隔离的服务副本
                        df_sx_01_tmp = df_sx_01[(df_sx_01['ISOLATION'] != 1) & (df_sx_01[machine_name_tmp2] >= 1)]
                        sorted_df_sx_01_tmp = df_sx_01_tmp.sort_values(by='COPY_SIZE', ascending=False)
                        sorted_df_sx_01_tmp = sorted_df_sx_01_tmp.reset_index(drop=True)
                        sorted_df_sx_01_tmp['TOTAL_R'] = sorted_df_sx_01_tmp[machine_name_tmp2] * sorted_df_sx_01_tmp[
                            'COPY_SIZE']
                        total_r_sum = sorted_df_sx_01_tmp['TOTAL_R'].sum()
                        # 判断该主机亲和的副本资源总量是否能装下这个副本
                        if total_r_sum + left_resource_true_tmp2 < copy_size_tmp:
                            print('这个主机装不了，换下一个主机')
                            a = a + 1
                            # 走主机循环
                            continue
                        else:
                            print('这个主机可以装')
                            rr = copy_size_tmp
                            dict_group5 = {}
                            for index2, row2 in sorted_df_sx_01_tmp.iterrows():
                                # 判断这个亲和服务的副本资源总量是否能装下
                                if row2['TOTAL_R'] + left_resource_true_tmp2 >= rr:
                                    n = math.ceil((rr - left_resource_true_tmp2) / row2['COPY_SIZE'])
                                    df_m_01.loc[machine_no_tmp2, 'RESOURCE_A'] = df_m_01.loc[machine_no_tmp2, 'RESOURCE_A'] + rr - n * row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp2, 'LEFT_RESOURCE'] = df_m_01.loc[machine_no_tmp2, 'LEFT_RESOURCE'] - rr + n * row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp2, 'LEFT_RESOURCE_TRUE'] = df_m_01.loc[machine_no_tmp2, 'LEFT_RESOURCE_TRUE'] - rr + n * row2['COPY_SIZE']
                                    df_sx_01.loc[service_no_tmp, machine_name_tmp2] = 1
                                    move_service_no_tmp = row2['SERVICE_NO']
                                    df_sx_01.loc[move_service_no_tmp, machine_name_tmp2] = df_sx_01.loc[move_service_no_tmp, machine_name_tmp2] - n
                                    df_out1.loc[df_out1['SERVICE_NAME'] == service_name_tmp, machine_name_tmp2] += 1

                                    # 需要挪走的先放到group5，最后和group4一起分配
                                    dict_group5['SERVICE_NAME'] = row2['SERVICE_NO']
                                    dict_group5['COPY_NUM2'] = n
                                    dict_group5['COPY_SIZE_TRUE'] = row2['COPY_SIZE']
                                    dict_group5['ISOLATION_TRUE'] = 0
                                    new_row2 = pd.Series(dict_group5)
                                    df_group5 = df_group5.append(new_row2, ignore_index=True)
                                    flag = True
                                    a = a + 1
                                    break
                                else:
                                    print('这个服务全部移走，并需要其他服务')
                                    n = row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp2, 'RESOURCE_A'] = df_m_01.loc[machine_no_tmp2, 'RESOURCE_A'] + rr - n * row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp2, 'LEFT_RESOURCE'] = df_m_01.loc[machine_no_tmp2, 'LEFT_RESOURCE'] - rr + n * row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp2, 'LEFT_RESOURCE_TRUE'] = df_m_01.loc[machine_no_tmp2, 'LEFT_RESOURCE_TRUE'] - rr + n * row2['COPY_SIZE']
                                    # df_sx_01.loc[service_no_tmp, machine_name_tmp2] = 1
                                    move_service_no_tmp = row2['SERVICE_NO']
                                    df_sx_01.loc[move_service_no_tmp, machine_name_tmp2] = df_sx_01.loc[move_service_no_tmp, machine_name_tmp2] - n
                                    rr = rr - n * row2['COPY_SIZE']
                                    dict_group5['SERVICE_NAME'] = row2['SERVICE_NAME']
                                    dict_group5['COPY_NUM2'] = n
                                    dict_group5['COPY_SIZE_TRUE'] = row2['COPY_SIZE']
                                    dict_group5['ISOLATION_TRUE'] = 0
                                    new_row2 = pd.Series(dict_group5)
                                    df_group5 = df_group5.append(new_row2, ignore_index=True)
                                    flag = True
                                    continue
                                # print(index2)
                            # 分配成功
                            # a = a + 1
                            # continue
                    # 如果分配成功就考虑下一个副本，跳出主机循环
                    if flag:
                        break
            # print('stop')
    #####################################group3
    # 判断group3是否为空
    success = df_group3.empty is False
    # success = True
    if success is False:
        # print('跳过df_group3')
        message = ''
    else:
        df_group3_tmp = df_group3.copy()
        #排序，优先分配副本多的服务
        sorted_df_group3_tmp = df_group3_tmp.sort_values(by='COPY_SIZE_TRUE', ascending=False)
        sorted_df_group3_tmp = sorted_df_group3_tmp.reset_index(drop=True)
        dict_sx_01 = {}
        for index, row in sorted_df_group3_tmp.iterrows():
            # 在服务df最后一行拼接上新服务
            print(row['SERVICE_NAME'])
            service_name_tmp = row['SERVICE_NAME']
            copy_size_tmp = row['COPY_SIZE_TRUE']
            copy_num2_tmp = int(row['COPY_NUM2'])
            dict_sx_01['SERVICE_NAME'] = service_name_tmp
            service_no_tmp = int(service_no_max + 1)
            dict_sx_01['SERVICE_NO'] = service_no_tmp
            service_no_max = service_no_max + 1
            dict_sx_01['COPY_NUM'] = copy_num2_tmp
            dict_sx_01['COPY_SIZE'] = copy_size_tmp
            dict_sx_01['ISOLATION'] = 0
            new_row = pd.Series(dict_sx_01)
            df_sx_01 = df_sx_01.append(new_row, ignore_index=True)
            df_sx_01.fillna(0, inplace=True)
            for i in range(0, copy_num2_tmp):
                # sorted_df_m_03 = df_m_01.sort_values(by='LEFT_RESOURCE_TRUE', ascending=False)
                sorted_df_m_03 = df_m_01.sort_values(by=['FLAG', 'LEFT_RESOURCE_TRUE'], ascending=[False, False])
                sorted_df_m_03 = sorted_df_m_03.reset_index(drop=True)
                machine_name_list_tmp3 = sorted_df_m_03['MACHINE_NAME'].tolist()
                machine_no_list_tmp3 = sorted_df_m_03['MACHINE_NO'].tolist()
                for j in range(0, len(sorted_df_m_03.index)):
                    print(j)
                    flag = False
                    machine_name_tmp3 = machine_name_list_tmp3[j]
                    machine_no_tmp3 = int(machine_no_list_tmp3[j])
                    left_resource_true_tmp3 = df_m_01.loc[machine_no_tmp3, 'LEFT_RESOURCE_TRUE']
                    if left_resource_true_tmp3 >= copy_size_tmp:
                        #当前主机能装下这个副本
                        df_m_01.loc[machine_no_tmp3, 'RESOURCE_A'] = df_m_01.loc[machine_no_tmp3, 'RESOURCE_A'] + copy_size_tmp
                        df_m_01.loc[machine_no_tmp3, 'LEFT_RESOURCE'] = df_m_01.loc[machine_no_tmp3, 'LEFT_RESOURCE'] - copy_size_tmp
                        df_m_01.loc[machine_no_tmp3, 'LEFT_RESOURCE_TRUE'] = df_m_01.loc[machine_no_tmp3, 'LEFT_RESOURCE_TRUE'] - copy_size_tmp
                        df_sx_01.loc[service_no_tmp, machine_name_tmp3] = df_sx_01.loc[service_no_tmp, machine_name_tmp3] + 1
                        df_out1.loc[df_out1['SERVICE_NAME'] == service_name_tmp, machine_name_tmp3] += 1

                        #分配成功
                        #跳出主机循环，进入下一个服务
                        flag = True
                    else:
                        print('当前主机剩余空间装不下这个副本，由于主机排序了，前一个装不下后一个也装不下，因此需要微调')
                        #该主机所有不需要隔离的服务副本
                        df_sx_01_tmp = df_sx_01[(df_sx_01['ISOLATION'] != 1) & (df_sx_01[machine_name_tmp3] >= 1)]
                        sorted_df_sx_01_tmp = df_sx_01_tmp.sort_values(by='COPY_SIZE', ascending=True)
                        sorted_df_sx_01_tmp = sorted_df_sx_01_tmp.reset_index(drop=True)
                        sorted_df_sx_01_tmp['TOTAL_R'] = sorted_df_sx_01_tmp[machine_name_tmp3] * sorted_df_sx_01_tmp['COPY_SIZE']
                        total_r_sum = sorted_df_sx_01_tmp['TOTAL_R'].sum()
                        #判断该主机亲和的副本资源总量是否能装下这个副本
                        if total_r_sum + left_resource_true_tmp3 < copy_size_tmp:
                            print('这个主机装不了，换下一个主机')
                            #走主机循环
                            continue
                        else:
                            print('这个主机可以装')
                            rr = copy_size_tmp
                            dict_group5 = {}
                            for index2, row2 in sorted_df_sx_01_tmp.iterrows():
                                # 判断这个亲和服务的副本资源总量是否能装下
                                if row2['TOTAL_R'] + left_resource_true_tmp3 >= rr:
                                    n = math.ceil((rr - left_resource_true_tmp3) / row2['COPY_SIZE'])
                                    df_m_01.loc[machine_no_tmp3, 'RESOURCE_A'] = df_m_01.loc[machine_no_tmp3, 'RESOURCE_A'] + rr - n * row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp3, 'LEFT_RESOURCE'] = df_m_01.loc[machine_no_tmp3, 'LEFT_RESOURCE'] - rr + n * row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp3, 'LEFT_RESOURCE_TRUE'] = df_m_01.loc[machine_no_tmp3, 'LEFT_RESOURCE_TRUE'] - rr + n * row2['COPY_SIZE']
                                    df_sx_01.loc[service_no_tmp, machine_name_tmp3] = df_sx_01.loc[service_no_tmp, machine_name_tmp3] + 1
                                    move_service_no_tmp = row2['SERVICE_NO']
                                    df_sx_01.loc[move_service_no_tmp, machine_name_tmp3] = df_sx_01.loc[move_service_no_tmp, machine_name_tmp3] - n
                                    df_out1.loc[df_out1['SERVICE_NAME'] == service_name_tmp, machine_name_tmp3] += 1

                                    #需要挪走的先放到group5，最后和group4一起分配
                                    dict_group5['SERVICE_NAME'] = row2['SERVICE_NAME']
                                    dict_group5['COPY_NUM2'] = n
                                    dict_group5['COPY_SIZE_TRUE'] = row2['COPY_SIZE']
                                    dict_group5['ISOLATION_TRUE'] = 0
                                    new_row2 = pd.Series(dict_group5)
                                    df_group5 = df_group5.append(new_row2, ignore_index=True)
                                    flag = True
                                    break
                                else:
                                    print('这个服务全部移走，并需要其他服务')
                                    n = row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp3, 'RESOURCE_A'] = df_m_01.loc[machine_no_tmp3, 'RESOURCE_A'] + rr - n * row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp3, 'LEFT_RESOURCE'] = df_m_01.loc[machine_no_tmp3, 'LEFT_RESOURCE'] - rr + n * row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp3, 'LEFT_RESOURCE_TRUE'] = df_m_01.loc[machine_no_tmp3, 'LEFT_RESOURCE_TRUE'] - rr + n * row2['COPY_SIZE']
                                    # df_sx_01.loc[service_no_tmp, machine_name_tmp3] = df_sx_01.loc[service_no_tmp, machine_name_tmp3] + 1
                                    move_service_no_tmp = row2['SERVICE_NO']
                                    df_sx_01.loc[move_service_no_tmp, machine_name_tmp3] = df_sx_01.loc[move_service_no_tmp, machine_name_tmp3] - n
                                    rr = rr - n * row2['COPY_SIZE']
                                    dict_group5['SERVICE_NAME'] = row2['SERVICE_NO']
                                    dict_group5['COPY_NUM2'] = n
                                    dict_group5['COPY_SIZE_TRUE'] = row2['COPY_SIZE']
                                    dict_group5['ISOLATION_TRUE'] = 0
                                    new_row2 = pd.Series(dict_group5)
                                    df_group5 = df_group5.append(new_row2, ignore_index=True)
                                    flag = True
                                    continue
                                # print(index2)
                            #分配成功
                            # continue
                    #如果分配成功就考虑下一个副本，跳出主机循环
                    if flag:
                        break
            print('stop')
    ##########################group4
    # 判断group4是否为空
    success = df_group4.empty is False
    # success = True
    if success is False:
        # print('跳过df_group4')
        message = ''
    else:
        df_group4_tmp = df_group4.copy()
        # 拼接service_no
        df_service_no = df_sx_01.copy()
        df_service_no = df_service_no[['SERVICE_NAME', 'SERVICE_NO']]
        v = ['SERVICE_NAME']
        df_group4_tmp = pd.merge(df_group4_tmp, df_service_no, on=v, how='left')
        sorted_df_group4_tmp = df_group4_tmp.sort_values(by='COPY_SIZE_TRUE', ascending=False)
        sorted_df_group4_tmp = sorted_df_group4_tmp.reset_index(drop=True)

        for index, row in sorted_df_group4_tmp.iterrows():
            # 在服务df最后一行拼接上新服务
            print(row['SERVICE_NAME'])
            service_name_tmp = row['SERVICE_NAME']
            copy_num2_tmp = int(row['COPY_NUM2'])
            service_no_tmp = int(row['SERVICE_NO'])
            copy_size_tmp = row['COPY_SIZE_TRUE']
            df_sx_01.loc[service_no_tmp, 'COPY_NUM'] = df_sx_01.loc[service_no_tmp, 'COPY_NUM'] + copy_num2_tmp
            # 读取该服务没有部署的主机,还能用的主机


            for i in range(0, copy_num2_tmp):
                # sorted_df_m_04 = df_m_01.sort_values(by='LEFT_RESOURCE_TRUE', ascending=False)
                sorted_df_m_04 = df_m_01.sort_values(by=['FLAG', 'LEFT_RESOURCE_TRUE'], ascending=[False, False])
                sorted_df_m_04 = sorted_df_m_04.reset_index(drop=True)
                machine_name_list_tmp4 = sorted_df_m_04['MACHINE_NAME'].tolist()
                machine_no_list_tmp4 = sorted_df_m_04['MACHINE_NO'].tolist()
                for j in range(0, len(sorted_df_m_04.index)):
                    # print(j)
                    flag = False
                    machine_name_tmp4 = machine_name_list_tmp4[j]
                    machine_no_tmp4 = int(machine_no_list_tmp4[j])
                    left_resource_true_tmp4 = df_m_01.loc[machine_no_tmp4, 'LEFT_RESOURCE_TRUE']
                    if left_resource_true_tmp4 >= copy_size_tmp:
                        # 当前主机能装下这个副本
                        df_m_01.loc[machine_no_tmp4, 'RESOURCE_A'] = df_m_01.loc[machine_no_tmp4, 'RESOURCE_A'] + copy_size_tmp
                        df_m_01.loc[machine_no_tmp4, 'LEFT_RESOURCE'] = df_m_01.loc[
                                                                            machine_no_tmp4, 'LEFT_RESOURCE'] - copy_size_tmp
                        df_m_01.loc[machine_no_tmp4, 'LEFT_RESOURCE_TRUE'] = df_m_01.loc[
                                                                                 machine_no_tmp4, 'LEFT_RESOURCE_TRUE'] - copy_size_tmp
                        df_sx_01.loc[service_no_tmp, machine_name_tmp4] = df_sx_01.loc[service_no_tmp, machine_name_tmp4] + 1
                        df_out1.loc[df_out1['SERVICE_NAME'] == service_name_tmp, machine_name_tmp4] += 1

                        # 分配成功
                        # 跳出主机循环，进入下一个服务
                        flag = True
                    else:
                        print('当前主机剩余空间装不下这个副本，由于主机排序了，前一个装不下后一个也装不下，因此需要微调')
                        # 该主机所有不需要隔离的服务副本
                        df_sx_01_tmp = df_sx_01[(df_sx_01['ISOLATION'] != 1) & (df_sx_01[machine_name_tmp3] >= 1)]
                        sorted_df_sx_01_tmp = df_sx_01_tmp.sort_values(by='COPY_SIZE', ascending=True)
                        sorted_df_sx_01_tmp = sorted_df_sx_01_tmp.reset_index(drop=True)
                        sorted_df_sx_01_tmp['TOTAL_R'] = sorted_df_sx_01_tmp[machine_name_tmp4] * sorted_df_sx_01_tmp[
                            'COPY_SIZE']
                        total_r_sum = sorted_df_sx_01_tmp['TOTAL_R'].sum()
                        # 判断该主机亲和的副本资源总量是否能装下这个副本
                        if total_r_sum + left_resource_true_tmp4 < copy_size_tmp:
                            print('这个主机装不了，换下一个主机')
                            # 走主机循环
                            continue
                        else:
                            print('这个主机可以装')
                            rr = copy_size_tmp
                            dict_group5 = {}
                            for index2, row2 in sorted_df_sx_01_tmp.iterrows():
                                # 判断这个亲和服务的副本资源总量是否能装下
                                if row2['TOTAL_R'] + left_resource_true_tmp4 >= rr:
                                    n = math.ceil((rr - left_resource_true_tmp4) / row2['COPY_SIZE'])
                                    df_m_01.loc[machine_no_tmp4, 'RESOURCE_A'] = df_m_01.loc[
                                                                                     machine_no_tmp4, 'RESOURCE_A'] + rr - n * \
                                                                                 row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp4, 'LEFT_RESOURCE'] = df_m_01.loc[
                                                                                        machine_no_tmp4, 'LEFT_RESOURCE'] - rr + n * \
                                                                                    row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp4, 'LEFT_RESOURCE_TRUE'] = df_m_01.loc[
                                                                                             machine_no_tmp4, 'LEFT_RESOURCE_TRUE'] - rr + n * \
                                                                                         row2['COPY_SIZE']
                                    df_sx_01.loc[service_no_tmp, machine_name_tmp4] = df_sx_01.loc[
                                                                                          service_no_tmp, machine_name_tmp4] + 1
                                    move_service_no_tmp = row2['SERVICE_NO']
                                    df_sx_01.loc[move_service_no_tmp, machine_name_tmp4] = df_sx_01.loc[
                                                                                               move_service_no_tmp, machine_name_tmp4] - n
                                    df_out1.loc[df_out1['SERVICE_NAME'] == service_name_tmp, machine_name_tmp4] += 1

                                    # 需要挪走的先放到group5，最后和group4一起分配
                                    dict_group5['SERVICE_NAME'] = row2['SERVICE_NAME']
                                    dict_group5['COPY_NUM2'] = n
                                    dict_group5['COPY_SIZE_TRUE'] = row2['COPY_SIZE']
                                    dict_group5['ISOLATION_TRUE'] = 0
                                    new_row2 = pd.Series(dict_group5)
                                    df_group5 = df_group5.append(new_row2, ignore_index=True)
                                    flag = True
                                    break
                                else:
                                    print('这个服务全部移走，并需要其他服务')
                                    n = row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp4, 'RESOURCE_A'] = df_m_01.loc[
                                                                                     machine_no_tmp4, 'RESOURCE_A'] + rr - n * \
                                                                                 row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp4, 'LEFT_RESOURCE'] = df_m_01.loc[
                                                                                        machine_no_tmp4, 'LEFT_RESOURCE'] - rr + n * \
                                                                                    row2['COPY_SIZE']
                                    df_m_01.loc[machine_no_tmp4, 'LEFT_RESOURCE_TRUE'] = df_m_01.loc[
                                                                                             machine_no_tmp4, 'LEFT_RESOURCE_TRUE'] - rr + n * \
                                                                                         row2['COPY_SIZE']
                                    # df_sx_01.loc[service_no_tmp, machine_name_tmp4] = df_sx_01.loc[
                                    #                                                       service_no_tmp, machine_name_tmp4] + 1
                                    move_service_no_tmp = row2['SERVICE_NO']
                                    df_sx_01.loc[move_service_no_tmp, machine_name_tmp4] = df_sx_01.loc[
                                                                                               move_service_no_tmp, machine_name_tmp4] - n
                                    rr = rr - n * row2['COPY_SIZE']
                                    dict_group5['SERVICE_NAME'] = row2['SERVICE_NO']
                                    dict_group5['COPY_NUM2'] = n
                                    dict_group5['COPY_SIZE_TRUE'] = row2['COPY_SIZE']
                                    dict_group5['ISOLATION_TRUE'] = 0
                                    new_row2 = pd.Series(dict_group5)
                                    df_group5 = df_group5.append(new_row2, ignore_index=True)
                                    flag = True
                                    continue
                                # print(index2)
                            # 分配成功
                            # continue
                    # 如果分配成功就考虑下一个副本，跳出主机循环
                    if flag:
                        break
            print('stop')

    df_out1['COPY_SIZE2'] = df_out1['COPY_SIZE2'] / 2
    printtime('突发流量服务分配方案')
    # print(df_out1)
    print(tabulate(df_out1, headers="keys", tablefmt="pretty"))

    # plan_dict_list2 = []
    # for index, row in df_out1.iterrows():
    #     # print(index)
    #     plan_dict_tmp2 = {}
    #     for i in range(0, len(machine_name_list)):
    #         machine_name_tmp = machine_name_list[i]
    #         service_count_tmp = row[machine_name_tmp]
    #         plan_dict_tmp2[machine_name_tmp] = service_count_tmp
    #     print(plan_dict_tmp2)
    #     plan_dict_list2.append(str(plan_dict_tmp2))
    # df_out1 = df_out1[['SERVICE_NAME', 'COPY_NUM2', 'COPY_SIZE2', 'ISOLATION2']]
    # df_out1['PLAN'] = plan_dict_list2
    #
    #
    #
    #
    #
    #
    # ############################################5
    # success = df_group5.empty is False
    # # success = True
    # if success is False:
    #     # print('跳过df_group5')
    #     message = ''
    # else:
    #
    #     df_group5_tmp = df_group5.copy()
    #     # 拼接service_no
    #     df_service_no = df_sx_01.copy()
    #     df_service_no = df_service_no[['SERVICE_NAME', 'SERVICE_NO']]
    #     v = ['SERVICE_NAME']
    #     df_group5_tmp = pd.merge(df_group5_tmp, df_service_no, on=v, how='left')
    #     sorted_df_group5_tmp = df_group5_tmp.sort_values(by='COPY_SIZE_TRUE', ascending=False)
    #     sorted_df_group5_tmp = sorted_df_group5_tmp.reset_index(drop=True)
    #     for index, row in sorted_df_group5_tmp.iterrows():
    #         # 在服务df最后一行拼接上新服务
    #         print(row['SERVICE_NAME'])
    #         service_name_tmp = row['SERVICE_NAME']
    #         copy_num2_tmp = int(row['COPY_NUM2'])
    #         service_no_tmp = int(row['SERVICE_NO'])
    #         copy_size_tmp = row['COPY_SIZE_TRUE']
    #         df_sx_01.loc[service_no_tmp, 'COPY_NUM'] = df_sx_01.loc[service_no_tmp, 'COPY_NUM'] + copy_num2_tmp
    #         # 读取该服务没有部署的主机,还能用的主机
    #
    #
    #         for i in range(0, copy_num2_tmp):
    #             # 第五组从小的机器开始放
    #             # sorted_df_m_05 = df_m_01.sort_values(by='LEFT_RESOURCE_TRUE', ascending=True)
    #             sorted_df_m_05 = df_m_01.sort_values(by=['FLAG', 'LEFT_RESOURCE_TRUE'], ascending=[False, True])
    #
    #             sorted_df_m_05 = sorted_df_m_05.reset_index(drop=True)
    #             machine_name_list_tmp5 = sorted_df_m_05['MACHINE_NAME'].tolist()
    #             machine_no_list_tmp5 = sorted_df_m_05['MACHINE_NO'].tolist()
    #             for j in range(0, len(sorted_df_m_05.index)):
    #                 # print(j)
    #                 flag = False
    #                 machine_name_tmp5 = machine_name_list_tmp5[j]
    #                 machine_no_tmp5 = int(machine_no_list_tmp5[j])
    #                 left_resource_true_tmp5 = df_m_01.loc[machine_no_tmp5, 'LEFT_RESOURCE_TRUE']
    #                 if left_resource_true_tmp5 >= copy_size_tmp:
    #                     # 当前主机能装下这个副本
    #                     df_m_01.loc[machine_no_tmp5, 'RESOURCE_A'] = df_m_01.loc[
    #                                                                      machine_no_tmp5, 'RESOURCE_A'] + copy_size_tmp
    #                     df_m_01.loc[machine_no_tmp5, 'LEFT_RESOURCE'] = df_m_01.loc[
    #                                                                         machine_no_tmp5, 'LEFT_RESOURCE'] - copy_size_tmp
    #                     df_m_01.loc[machine_no_tmp5, 'LEFT_RESOURCE_TRUE'] = df_m_01.loc[
    #                                                                              machine_no_tmp5, 'LEFT_RESOURCE_TRUE'] - copy_size_tmp
    #                     df_sx_01.loc[service_no_tmp, machine_name_tmp5] = df_sx_01.loc[
    #                                                                           service_no_tmp, machine_name_tmp5] + 1
    #                     # 分配成功
    #                     # 跳出主机循环，进入下一个服务
    #                     flag = True
    #
    #                 if flag:
    #                     break
    #         print('stop')
    #
    #     ####生成df_out2
    #     sorted_df_group5_tmp2 = df_group5_tmp.sort_values(by='SERVICE_NO', ascending=True)
    #     sorted_df_group5_tmp2 = sorted_df_group5_tmp2.reset_index(drop=True)
    #     my_list = sorted_df_group5_tmp2['SERVICE_NAME'].tolist()
    #     new_list = []
    #     for item in my_list:
    #         if item not in new_list:
    #             new_list.append(item)
    #     print(new_list)
    #     old_df = df_sx_new.loc[df_sx_new['SERVICE_NAME'].isin(new_list)]
    #     new_df = df_sx_01.loc[df_sx_01['SERVICE_NAME'].isin(new_list)]
    #     plan_dict_list3 = []
    #     for index, row in new_df.iterrows():
    #         print(index)
    #         plan_dict_tmp3 = {}
    #         for i in range(0, len(machine_name_list)):
    #             machine_name_tmp = machine_name_list[i]
    #             service_count_tmp = row[machine_name_tmp]
    #             plan_dict_tmp3[machine_name_tmp] = service_count_tmp
    #         print(plan_dict_tmp3)
    #         plan_dict_list3.append(str(plan_dict_tmp3))
    #     new_df2 = new_df[['SERVICE_NAME']]
    #     new_df2['NEW_PLAN'] = plan_dict_list3
    #     v = ['SERVICE_NAME']
    #     df_out2 = pd.merge(old_df, new_df2, on=v, how='left')
    #     df_out2.drop(['SERVICE_NO'], axis=1, inplace=True)
    #
    #     print('stop')
    # df_out1['COPY_SIZE2'] = df_out1['COPY_SIZE2'] / 2
    # writer = pd.ExcelWriter('临时服务分配方案.xlsx')
    # df_out1.to_excel(writer, sheet_name='Sheet1', index=False)
    # writer.save()
    # df_out2['COPY_SIZE'] = df_out2['COPY_SIZE'] / 2
    # # writer = pd.ExcelWriter('旧服务需要调整.xlsx')
    # # df_out2.to_excel(writer, sheet_name='Sheet1', index=False)
    # # writer.save()
    # print('临时服务分配方案')
    # print(df_out1)
    # # print('旧服务需要调整')
    # # print(df_out2)
    # message = '执行成功'
    table_1 = df_out1.to_dict(orient='records')
    table_2 = df_out2.to_dict(orient='records')
    return message, table_1, table_2
if __name__ == '__main__':
    start = datetime.datetime.now()
    message, table_1, table_2 = main(type=1)
    # print(message, table_1)
    elapsed = float((datetime.datetime.now() - start).seconds)
    # print("Time Used 4 All ----->>>> %f seconds" % (elapsed))
    # print('finish')



